<?php

namespace backend\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use Yii;

/**
 * This is the model class for table "{{%backend_user}}".
 *
 * @property int $id
 * @property string $username
 * @property string $auth_key
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property int $status
 * @property int $created_at
 * @property int $updated_at
 */
class BackendUser extends ActiveRecord implements IdentityInterface {

    public $password;
    public $re_password;

    /**
     * @inheritdoc
     */
    public static function tableName() {
        return '{{%backend_user}}';
    }

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['username', 'email', 'password', 're_password'], 'required', 'on' => 'create'],
            [['password'],'string','max'=>32],
            [['username', 'email'], 'required', 'on' => 'update'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['username'], 'string', 'max' => 32],
            ['username', 'unique', 'targetClass' => '\backend\models\BackendUser'],
            ['email', 'unique', 'targetClass' => '\backend\models\BackendUser'],
            [['created_at', 'updated_at'], 'default', 'value' => time()],
            [['re_password'], 'compare', 'compareAttribute' => 'password'],
            [['email'], 'email'],
        ];
    }

    /**
     * @inheritdoc
     * 根据user_backend表的主键（id）获取用户
     */
    public static function findIdentity($id) {
        return static::findOne(['id' => $id]);
    }

    /**
     * @inheritdoc
     * 根据access_token获取用户
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('findIdentityByAccessToken" is not implemented.');
    }
    /**
     * 读取当前登录用户所属的父ID
     * @return int $userid  
     */    
    public static function getParentUserId(){
        $user = Yii::$app->user->getIdentity();
        $userid = $user->parent;
        if(empty($userid)){
            $userid = $user->id;
        }
        return $userid;        
    }
    /**
     * @inheritdoc
     * 用以标识 Yii::$app->user->id 的返回值
     */
    public function getId() {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     * 获取auth_key
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     * 验证auth_key
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * 根据user_backend表的username获取用户
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username) {
        return static::findOne(['username' => $username]);
    }

    /**
     * 验证密码的准确性
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * 添加新用户
     * @return boolean 添加成功返回true
     */
    public function signup() {
        if ($this->validate()) {
            $this->type = Yii::$app->id;
            $this->auth_key = Yii::$app->security->generateRandomString();
            if ($this->password) {
                $this->password_hash = Yii::$app->security->generatePasswordHash($this->password);
            }

            return $this->save(false);
        }
        return false;
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'id' => Yii::t('common', 'ID'),
            'username' => Yii::t('common', 'Username'),
            'auth_key' => Yii::t('common', 'Auth Key'),
            'password_hash' => Yii::t('common', 'Password Hash'),
            'password_reset_token' => Yii::t('common', 'Password Reset Token'),
            'email' => Yii::t('common', 'Email'),
            'status' => Yii::t('common', 'Status'),
            'created_at' => Yii::t('common', 'Created At'),
            'updated_at' => Yii::t('common', 'Updated At'),
            'password' => Yii::t('common', 'Password'),
            're_password' => Yii::t('common', 'Repeat Password'),
        ];
    }

}
